package com.hrsystem.service;

import com.hrsystem.entity.User;
import com.hrsystem.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User login(User user) {
        User loginUser = userMapper.getUserByAccount(user.getAccount());
        String newPwd = DigestUtils.md5DigestAsHex((user.getPassword() + "hrzp6666").getBytes());
        if (loginUser != null && loginUser.getPassword().equals(newPwd)) {
            String userToken = UUID.randomUUID().toString();
            userMapper.setTokenToUser(userToken, loginUser.getId());
            loginUser.setToken(userToken);
            return loginUser;
        } else {
            return null;
        }
    }

    public User register(User user) {
        if (userMapper.getUserByAccount(user.getAccount()) != null) {
            return null;
        }
        String newPwd = DigestUtils.md5DigestAsHex((user.getPassword() + "hrzp6666").getBytes());
        user.setPassword(newPwd);
        boolean isSuccess = userMapper.register(user)>0;
        System.out.println("插入一条数据，ID是：" + user.getId());
        if (isSuccess) {
            return user;
        } else {
            return null;
        }
    }

    public User getUserByToken(HttpServletRequest request) {
        String token = request.getHeader("TOKEN");
        System.out.println("这是token"+token);
        if (token == null) {
            return null;
        }
        return userMapper.getUserByToken(token);
    }
}
